<?php

namespace App\Http\Controllers\Asset;

use App\Http\Controllers\pagniateable;
use App\Http\Resources\CommonModelResource;
use App\Models\AssetStock;
use App\Models\AssetStockChangeHistory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AssetStockChangeHistoryController extends Controller
{
    use pagniateable;

    public function list($assetStockId)
    {
        $query = AssetStockChangeHistory::whereAssetStockId($assetStockId);
        return $this->paginate($query);
    }

    public function add($assetStockId)
    {
        $user = auth()->user();
        $assetStock = AssetStock::findOrFail($assetStockId);
        $quantity = intval(request()->get('quantity'));
        $actionId = intval(request()->get('action_id'));
        $comment = request()->get('comment');
        if ($actionId != 1 && $quantity > 0) {
            $quantity = -1 * $quantity;
        }
        $result = AssetStockChangeHistory::create([
            "action_id" => $actionId,
            "asset_stock_id" => $assetStock->id,
            "comment" => $comment,
            "quantity" => $quantity,
            "user_id" => $user->id
        ]);
        $assetStock->available_quantity = $assetStock->available_quantity + $quantity;
        $assetStock->total_quantity = $assetStock->total_quantity + $quantity;
        $assetStock->save();
        return response()->json(compact(['result']));
    }
}
